import 'package:flutter/material.dart';
import 'package:flutter_house_manager/controller/build_controller.dart';
import 'package:flutter_house_manager/pages/Home/index.dart';
import 'package:flutter_house_manager/pages/Mine/index.dart';
import 'package:flutter_house_manager/utils/Emitter.dart';
import 'package:flutter_house_manager/utils/TokenManager.dart';
import 'package:get/get.dart';

class TabsPage extends StatefulWidget {
  const TabsPage({super.key});

  @override
  _TabsPageState createState() => _TabsPageState();
}

class _TabsPageState extends State<TabsPage> {
  // 当前激活的索引
  int _currentIndex = 0;
  // 底部导航栏数据
  final List _tabList = [
    {
      "label": '首页',
      "icon": "assets/tabs/home_default.png",
      "active_icon": "assets/tabs/home_active.png"
    },
    {
      "label": '我的',
      "icon": "assets/tabs/my_default.png",
      "active_icon": "assets/tabs/my_active.png"
    }
  ];
    /// 目的是: 添加和编辑房屋都需要用到这个控制器, 所以把控制器的加入提前到tabs页面
  BuildController buildController = Get.put<BuildController>(BuildController());
  //返回底部tabs中的item
  List<BottomNavigationBarItem> _getTabsBar() {
    List<BottomNavigationBarItem> list = [];
    for (var item in _tabList) {
      list.add(BottomNavigationBarItem(
          icon: Image.asset(item["icon"] as String, width: 30, height: 30),
          activeIcon:
              Image.asset(item["active_icon"] as String, width: 30, height: 30),
          label: item["label"] as String));
    }
    return list;
  }

  @override
  void initState() {
    super.initState();
    tokenManager.init();
    registerEvent();
  }

  registerEvent() {
    emitter.on<LogoutEvent>().listen((params) {
      // 1.1 清除token
      tokenManager.removeToken();
      // 1.2 跳转到登录页
      Navigator.pushNamed(context, "/login");
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: IndexedStack(
        index: _currentIndex,
        children: [
          const HomePage(),
          MinePage(
            currentIndex: _currentIndex,
          )
        ],
      )),
      bottomNavigationBar: BottomNavigationBar(
          backgroundColor: Colors.white,
          selectedItemColor: const Color.fromARGB(255, 85, 145, 175),
          items: _getTabsBar(),
          currentIndex: _currentIndex,
          onTap: (index) {
            setState(() {
              _currentIndex = index;
            });
          }),
    );
  }
}
